package henu.graduation_design.onlineshop;

import java.util.HashMap;
import java.util.Map;

import henu.graduation_design.util.Encrypt;
import henu.graduation_design.util.JsonLoader;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.AnimationDrawable;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class LoginDialogActivity extends Activity {

	private JsonLoader jsonLoader = new JsonLoader();
	int login = 0;
	String account;
	String pwd;
	Intent intent;
	boolean isRememberMe;

	private ViewSwitcher mViewSwitcher;
	private ImageButton btn_close;
	private Button btn_login;
	private AutoCompleteTextView mAccount;
	private EditText mPwd;
	private AnimationDrawable loadingAnimation;
	private View loginLoading;
	private CheckBox chb_rememberMe;
	private InputMethodManager imm;

	private void loadJson(final String url, final Map<String,Object> mapEntry) {
		jsonLoader.postJson(url, null,  mapEntry,
				new JsonLoader.JsonObjectCallback() {
					public void jsonLoaded(JSONObject jsonObject) {
						try {
							login = jsonObject.getInt("UserLoginResult");
						} catch (JSONException e) {
							e.printStackTrace();
						}
						if (login!=0) {
							SharedPreferences sp = getSharedPreferences("SP",
									MODE_PRIVATE);
							// 存入数据
							Editor editor = sp.edit();
							editor.putBoolean("IsLogin", true);
							editor.putInt("UserID", login);
							editor.putString("UserName", account);
							editor.putString("Password", Encrypt.MD5(pwd));
							editor.commit();
							intent.putExtra("isLogin", true);
							setResult(RESULT_OK, intent);
							finish();
						} else {
							Toast.makeText(getApplicationContext(), "账号或密码错误",
									Toast.LENGTH_LONG).show();
							mPwd.setText("");
							mViewSwitcher.showPrevious();
						}
					}
				});
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login_dialog);
		intent = this.getIntent();
		imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

		mViewSwitcher = (ViewSwitcher) findViewById(R.id.logindialog_view_switcher);
		loginLoading = (View) findViewById(R.id.login_loading);
		mAccount = (AutoCompleteTextView) findViewById(R.id.login_account);
		mPwd = (EditText) findViewById(R.id.login_password);
		chb_rememberMe = (CheckBox) findViewById(R.id.login_checkbox_rememberMe);

		SharedPreferences sp = getSharedPreferences("SP", MODE_PRIVATE);
		if (sp.getBoolean("RememberMe", false)) {
			mAccount.setText(sp.getString("UserName", ""));
		}

		btn_close = (ImageButton) findViewById(R.id.login_close_button);
		btn_close.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		btn_login = (Button) findViewById(R.id.login_btn_login);
		btn_login.setOnClickListener(new View.OnClickListener() {
			@SuppressLint({ "NewApi", "CommitPrefEdits" })
			public void onClick(View v) {
				// 隐藏软键盘
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

				account = mAccount.getText().toString();
				pwd = mPwd.getText().toString();
				isRememberMe = chb_rememberMe.isChecked();

				SharedPreferences sp = getSharedPreferences("SP", MODE_PRIVATE);
				// 存入数据
				Editor editor = sp.edit();
				editor.putBoolean("RememberMe", isRememberMe);
				editor.commit();

				// 判断输入
				if (account.isEmpty()) {
					Toast.makeText(getApplicationContext(), "请输入账户",
							Toast.LENGTH_LONG).show();
					return;
				}
				if (pwd.isEmpty()) {
					Toast.makeText(getApplicationContext(), "请输入密码",
							Toast.LENGTH_LONG).show();
					return;
				}

				btn_close.setVisibility(View.GONE);
				loadingAnimation = (AnimationDrawable) loginLoading
						.getBackground();
				loadingAnimation.start();
				mViewSwitcher.showNext();

				try {
				    Map<String,Object> mapEntry=new HashMap<String, Object>();
					mapEntry.put("userName", account);
					mapEntry.put("password", Encrypt.MD5(pwd));
					loadJson(getString(R.string.url_login), mapEntry);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_login_dialog, menu);
		return true;
	}

}
